package main

import "gopkg.in/mgo.v2"

// DBOperation 数据库操作类
type DBOperation struct {
	session *mgo.Session
	dbName  string
	cfg     *Config
}

// NewDBOperation 创建新的数据库操作类
func NewDBOperation(cfg *Config) (*DBOperation, error) {
	zLog("数据库连接::", cfg.DBUrl, " 开始")
	session, err := mgo.Dial(cfg.DBUrl)
	if err != nil {
		zLogError(nil, "数据库连接失败::", err.Error())
		return nil, err
	}
	if cfg.DBUser != "" && cfg.DBPwd != "" {
		err = session.Login(&mgo.Credential{
			Username: cfg.DBUser,
			Password: cfg.DBPwd,
		})
		if err != nil {
			zLogError("数据库登录失败::", err.Error())
			return nil, err
		}
	}
	session.SetPoolLimit(10) //设置连接缓冲池的最大值

	dbo := DBOperation{session: session, dbName: cfg.DBName, cfg: cfg}

	return &dbo, nil
}

// Close the database
func (p *DBOperation) Close() {
	p.session.Close()
}
